#include <iostream>
#include <vector>
#include <string>
#include <thread>
#include <mutex>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/resource.h>
#include <atomic>
#include <chrono>
#include <string.h>

// 配置参数
const char* SERVER_IP = "127.0.0.1";  // 服务器IP（本地测试用127.0.0.1）
const int BASE_PORT = 8080;           // 服务器基础端口（8080~8090）
const int PORT_COUNT = 11;            // 端口数量（8080~8090共11个）
const int TOTAL_CONNECTIONS = 60000;  // 总连接数（改为60000）
const int CONNS_PER_THREAD = 1000;    // 每个线程创建的连接数
const int HEARTBEAT_INTERVAL = 30;    // 心跳间隔（秒）

// 统计信息
std::atomic<int> total_success(0);
std::atomic<int> total_failure(0);
std::mutex cout_mutex;

// 设置非阻塞模式
bool setNonBlocking(int fd) {
    int flags = fcntl(fd, F_GETFL, 0);
    if (flags == -1) { perror("fcntl F_GETFL"); return false; }
    if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
        perror("fcntl F_SETFL O_NONBLOCK");
        return false;
    }
    return true;
}

// 单个线程创建连接的函数
void createConnections(int thread_id) {
    std::vector<int> sockets;
    sockets.reserve(CONNS_PER_THREAD);

    // 循环创建连接
    for (int i = 0; i < CONNS_PER_THREAD; ++i) {
        // 轮询使用服务器端口（8080~8090）
        int port = BASE_PORT + (i % PORT_COUNT);
        
        // 创建socket
        int sock = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
        if (sock == -1) {
            perror("socket creation failed");
            sleep(1);  // 避免频繁失败
            continue;
        }

        // 设置非阻塞（加速连接建立）
        setNonBlocking(sock);

        // 连接服务器
        struct sockaddr_in server_addr;
        memset(&server_addr, 0, sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
        server_addr.sin_port = htons(port);

        // 非阻塞connect（立即返回，后续检查连接结果）
        connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr));

        // 检查连接是否成功
        int error = 0;
        socklen_t len = sizeof(error);
        if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error != 0) {
            close(sock);
            continue;
        }

        sockets.push_back(sock);

        // 每创建1000个连接打印进度
        if ((i + 1) % 1000 == 0) {
            std::lock_guard<std::mutex> lock(cout_mutex);
            std::cout << "Thread " << thread_id 
                      << " created " << (i + 1) << " connections" << std::endl;
        }
    }

    std::lock_guard<std::mutex> lock(cout_mutex);
    std::cout << "Thread " << thread_id 
              << " finished creating connections. Total: " << sockets.size() << std::endl;

    // 心跳循环（保持连接）
    while (true) {
        for (int sock : sockets) {
            if (sock == -1) continue;

            // 发送心跳包（简单字符串）
            std::string heartbeat = "heartbeat from thread " + std::to_string(thread_id);
            ssize_t sent = send(sock, heartbeat.c_str(), heartbeat.size(), 0);
            
            // 处理断开的连接（重连）
            if (sent == -1) {
                std::lock_guard<std::mutex> lock(cout_mutex);
                std::cerr << "Thread " << thread_id 
                          << " socket " << sock << " disconnected. Reconnecting..." << std::endl;
                close(sock);
                
                // 重新创建连接
                int new_sock = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
                setNonBlocking(new_sock);
                struct sockaddr_in server_addr;
                memset(&server_addr, 0, sizeof(server_addr));
                server_addr.sin_family = AF_INET;
                server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
                server_addr.sin_port = htons(BASE_PORT + (rand() % PORT_COUNT));
                connect(new_sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
                
                // 检查重连是否成功
                int error = 0;
                socklen_t len = sizeof(error);
                if (getsockopt(new_sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error != 0) {
                    close(new_sock);
                    continue;
                }
                
                sock = new_sock;
                total_failure++;
            } else {
                total_success++;
            }
        }
        sleep(HEARTBEAT_INTERVAL);
    }
}

int main() {
    // 检查系统文件描述符限制
    struct rlimit rlim;
    if (getrlimit(RLIMIT_NOFILE, &rlim) == 0) {
        std::cout << "当前文件描述符限制: 软限制=" << rlim.rlim_cur 
                  << ", 硬限制=" << rlim.rlim_max << std::endl;
        
        if (rlim.rlim_cur < TOTAL_CONNECTIONS + 1000) {
            std::cerr << "错误: 文件描述符限制不足，无法创建" << TOTAL_CONNECTIONS << "个连接" << std::endl;
            std::cerr << "请先执行: ulimit -n " << (TOTAL_CONNECTIONS + 10000) << std::endl;
            return 1;
        }
    }

    // 计算需要的线程数
    int num_threads = TOTAL_CONNECTIONS / CONNS_PER_THREAD;
    if (TOTAL_CONNECTIONS % CONNS_PER_THREAD != 0) {
        num_threads++;
    }

    std::cout << "启动 " << num_threads << " 个线程，创建 " << TOTAL_CONNECTIONS << " 个连接" << std::endl;

    // 创建线程
    std::vector<std::thread> threads;
    for (int i = 0; i < num_threads; ++i) {
        threads.emplace_back(createConnections, i);
    }

    // 等待所有线程完成（防止僵尸线程）
    for (auto& t : threads) t.join();

    return 0;
}